package com.kk.springcloud.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
@Slf4j
public class PreLogFilter extends ZuulFilter {

    /**
     * 定义过滤器的类型
     * pre:在请求被路由之前执行
     * route:在路由请求的时候执行
     * post:请求路由以后执行
     * error:处理请求时发生错误的时候执行
     *
     * @return 过滤器的类型
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 过滤器执行的顺序，配置多个有顺序的过滤
     * 执行顺序从小到大
     *
     * @return 执行顺序
     */
    @Override
    public int filterOrder() {
        // 优先级为0，数字越大，优先级越低 
        return 1;
    }

    /**
     * 是否开启过滤器
     * true:开启
     * false:禁用
     *
     * @return 是否开启过滤器
     */
    @Override
    public boolean shouldFilter() {
        // 是否开启
        return true;
    }

    /**
     * 过滤器的业务实现
     *
     * @return null 没有意义
     * @throws ZuulException 异常信息
     */
    @Override
    public Object run() throws ZuulException {
        // 业务逻辑代码
        RequestContext requestContext = RequestContext.getCurrentContext ( );
        HttpServletRequest request = requestContext.getRequest ( );
        String host = request.getRemoteHost ( );
        String method = request.getMethod ( );
        String uri = request.getRequestURI ( );
        log.info("=====> Remote host:{},method:{},uri:{}", host, method, uri);
        System.out.println ("********" + new Date ( ).getTime ( ));
        return null;
    }
}
